﻿using AutoMapper;
using MediatR;
using Traceability.App.API.Application.Command.Immune;
using Traceability.App.Domain.Entities;
using Traceability.App.ErrorCode;
using Traceability.App.Infrastructure.Interface;

namespace Traceability.App.API.Application.Handler.Immune
{
    /// <summary>
    /// 修改免疫信息请求命令处理类
    /// </summary>
    public class UpdateImmuneHandler:IRequestHandler<UpdateImmuneCommand,ApiResult<int>>
    {
        IBaseRepository<Immune_Information> immuneRep;
        IMapper mapper;

        public UpdateImmuneHandler(IBaseRepository<Immune_Information> immuneRep, IMapper mapper)
        {
            this.immuneRep = immuneRep;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(UpdateImmuneCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> res = new ApiResult<int>();

                var immune = immuneRep.GetAll().Where(x => x.Id == request.id && !x.IsDeleted).FirstOrDefault();
                if (immune == null)
                {
                    res.Msg = "免疫信息不存在";
                    res.Code = ApiEnum.Fail;
                    return Task.FromResult(res);
                }
                var model=mapper.Map(request, immune);
                int r = immuneRep.UpdateAsync(model).Result;
                if (r > 0)
                {
                    res.Msg = "免疫信息修改成功";
                    res.Code = ApiEnum.Success;
                    res.Data = r;
                }
                else
                {
                    res.Msg = "免疫信息修改失败";
                    res.Code = ApiEnum.Fail;
                }
                return Task.FromResult(res);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
